# -*- coding: utf-8 -*-
import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests,json
from common.helper import Helper
from urllib.parse import urlencode

class Spider(object):

    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "上海医保账户重大疾病保险"
    # 生成产品数据
    def genProductInfo(self):
        plan = {

            #年龄段
            "year":[str(i) for i in range(16,66)],
            #性别
            "gender":["M","F"],
            #保额
            "money":["100000","200000"],
            #保障期限
            "expire":["1年"]
        }
        for v in product(plan["year"],plan["gender"],plan["money"],plan["expire"]):
            #写入数据库
            self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(

                v[0],v[1],v[2],v[3]
            ))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(

                v[0],v[1],v[2],v[3]
            ) )

    #执行爬虫
    def requestJson(self,dt=None):

        data = {

            "pageName": "productAdd",
            "goods_id": "62566",
            "merchant_id": "B2C",
            "toubaoli_money":"",
            "productCode": "201909181000001",
            "productId": "5af11abf - f2a5 - 4899 - bac0 - 4423a258328d",
            "riskCode": "201909181000000",
            "productName": "上海医保账户重大疾病保险",
            "insuredPrice": "2261",
            "insured.birthday":"",
            "templateType": "1",
            "employee_id":"",
            "channel": "GWSC - MENU - M18",
            "empNo":"",
            "newsCode":"",
            "twoMonthInsuredPrice": "4522.00",
            "loginUserId":"",
            "trialBySexAndAge": "true",
            "insured.age": dt["year"],
            "insured.sex": "1" if dt["gender"] == "M" else "2",
            "policy.amount": dt["money"][::5],
            "policy.dateRemark":"1",
            "policy.showMessage": "false",
            "person.mobilenum": "承保短信将发送至您的手机"

        }

        payload = urlencode( data )

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)

        if r.status_code == 200 and "计算保费成功" in r.text:

            price = Helper.decimalParse( r.json()["totalPremium"])

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }

            self.mysql.updatePrice( data )

        else:

            #更新任务失败
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }

            self.mysql.updateTask( data )

            print("/*任务更新失败:%d*/"%dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)

if __name__ == '__main__':

    s = Spider()
    s.main()